<?php

namespace addons\shopro\controller;

use addons\shopro\exception\Exception;
use addons\shopro\model\Share as ShareModel;
use addons\shopro\model\User;
use think\Db;

class Share extends Base
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 获取分享记录
     *
     * @return void
     */
    public function index()
    {
        $params = $this->request->get();

        $shares = ShareModel::getList($params);
        return $this->success('获取成功', $shares);
    }


    public function add()
    {

        $spm = $this->request->post('spm');
        $share = false;
        if (!empty($spm)) {
            $share = \think\Db::transaction(function () use ($spm) {
                try {
                    $shareLog = ShareModel::add($spm);
                    if ($shareLog) {
                        \think\Hook::listen('share_after', $shareLog);
                        return true;
                    }
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                return false;
            });
        }
        if($share) {
            $this->success('识别成功'); // 使用 success 前端不提示
        }
    }
    // 生成二维码
    public function buildQrcode()
    {
        $user = User::info();
        //$text = cdnurl('https://shopro.zhongtaizhixun.com.cn/?parent_code='.$user->id,true);
        //$update['qrcode_image'] = \addons\service\library\Common::createQrcode($text);
        $update = self::ceshihtml($user->id);
        $re_data['image_url'] = $update;
        $this->success('成功',$re_data);
    }

    public function ceshihtml($mem_id)
    {
        $data = Db::name("service_project_configure")->find();
        $APPID = $data['userappid'];//小程序appid
        $APPSECRET = $data['usersecret'];//小程序秘钥
        //$access_token=$this->checkAuth($APPID,$APPSECRET);//获取access_token,没有这个不能生成的
        $access_token ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
        session_start();
        $_SESSION['access_token'] =$access_token;
        $_SESSION['expires_in'] = 0;
        $ACCESS_TOKEN ="";
        if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() >$_SESSION['expires_in']))
        {
            $json = $this->httpRequest($access_token);
            $json = json_decode($json,true);
            // var_dump($json);
            $_SESSION['access_token'] =$json['access_token'];
            $_SESSION['expires_in'] = time()+7100;
            $ACCESS_TOKEN =$json["access_token"];
        }
        else{
            $ACCESS_TOKEN = $_SESSION["access_token"];
        }
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx,透明底色'is_hyaline'=>true
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$ACCESS_TOKEN;//生成圆形二维码
        // $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";//生成方形二维码
        $param = json_encode(array("path"=>"pages/index/index?parent_user_id={$mem_id}","width"=> 150,'env_version'=>'release'));

        //POST参数
        $result = $this->httpRequest($qcode,$param,"POST");
        $path ='/public/third/qrcode/'.date("Y-m-d").'/';
        if (!is_dir(ROOT_PATH.$path))
        {
            mkdir(ROOT_PATH.$path,0777,true);
        }
        //生成二维码
        $filename= '/third/qrcode/'.date("Y-m-d").'/'.$mem_id . time() . '.png';
       // $filename= $mem_id . '.png';
        $ret = file_put_contents(ROOT_PATH."public/".$filename, $result, FILE_APPEND);
        return $filename;
        //下面是加密
        // $base64_image ="data:image/jpeg;base64,".base64_encode($result );
        // echo $base64_image;
        // return view($this->tmplDir . '.' . 'ceshihtml', $this->data);
    }
    //把请求发送到微信服务器换取二维码
    public function httpRequest($url,$data='',$method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data !='')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    //获取access_token
    public function checkAuth($appid,$appsecret){
        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $result = $this->http_get($url);
        if ($result){
            $json = json_decode($result,true);
            if (!$json || isset($json['errcode'])) {
                return false;
            }
            return $json['access_token'];
        }
        return false;
    }

    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
}
